﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LEET.CommonInterfaces.TestControls;
using Compiled_Tests;

namespace Compiled_Tests
{
    public class ActionEnumeration : IEnumerator<IAutomationActionResult>
    {
        Stack<IEnumerator<IAutomationActionResult>> stack;

        public ActionEnumeration()
        {
            stack = new Stack<IEnumerator<IAutomationActionResult>>();
            OnScriptFinished += delegate() { };
        }

        public IAutomationActionResult Current
        {
            get
            {
                IAutomationActionResult ret = stack.Peek().Current;
                if (FirstActionOfCurrentScript)
                    ret.IsFirstResult = true;
                return ret;
            }
        }

        public void Dispose()
        {
            foreach (IEnumerator<AutomationActionResult> e in stack)
            {
                e.Dispose();
            }
        }

        object System.Collections.IEnumerator.Current
        {
            get { return Current; }
        }

        public bool MoveNext()
        {
            if (stack.Count <= 0)
                return false;

            if (!stack.Peek().MoveNext())
            {
                stack.Pop().Dispose();
                OnScriptFinished();
                return MoveNext();
            }

            return true;
        }

        public void Reset()
        {
            throw new NotImplementedException();
        }

        ////////////////////////

        public delegate void TestScriptFinishedEvent();
        public event TestScriptFinishedEvent OnScriptFinished;

        public void AddTestScript(IEnumerable<IAutomationActionResult> script)
        {
            stack.Push(script.GetEnumerator());
            FirstActionOfCurrentScript = true;
        }

        private bool firstActionOfCurrentScript;
        private bool FirstActionOfCurrentScript
        {
            get
            {
                if (firstActionOfCurrentScript)
                {
                    firstActionOfCurrentScript = false;
                    return true;
                }
                return false;
            }
            set
            {
                firstActionOfCurrentScript = value;
            }
        }
    }
}
